package org.example.core.plugin;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;
import org.example.core.proxy.QueryResultProxy;
import org.springframework.util.CollectionUtils;

import java.sql.Statement;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.stream.Collectors;

@Intercepts(
        @Signature(type = ResultSetHandler.class,method = "handleResultSets",args = {Statement.class})
)
public class QueryInterceptor implements Interceptor  {

    private List<Class<?>> proxyClass ;

    public QueryInterceptor(List<Class<?>> proxyClass){
        this.proxyClass = proxyClass;
    }
    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object proceed = invocation.proceed();

        if(Objects.isNull(proceed)){return proceed;}

        if(proceed instanceof List ){
            List<?> list = (List<?>) proceed;
            if(CollectionUtils.isEmpty(list)){return proceed;}

            return list.stream().map(QueryResultProxy::create).collect(Collectors.toList());

        }else if(proxyClass.stream().anyMatch(proxy -> proxy.isAssignableFrom(proceed.getClass()))){
            return QueryResultProxy.create(proceed);
        }else {
            return proceed;
        }

    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }
}
